package com.spzx.product.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        int processors = Runtime.getRuntime().availableProcessors(); // 系统处理器个数
        int corePoolSize = processors;
        int maxPoolSize = processors * 2; // 最大线程数  (IO密集型 2*n, CPU密集型 n + 1 )
        long keepAliveTime = 60L;

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100), // 有界队列
                Executors.defaultThreadFactory(),  // 自定义工厂可以精确处理异常
                // TODO 重试次数
                (runnable, executor) -> { // 自定义拒绝策略, 等待重试
                    try {
                        TimeUnit.MILLISECONDS.sleep(200);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    executor.submit(runnable);
                }
        );

        return threadPoolExecutor;
    }

}
